var ws = require("nodejs-websocket");
var playerProto = require('./player')

function main() {
    createWsServer(4396)
}

function createWsServer(port) {
    console.log(`创建本地websocket,port:  ${port}`);
    //websocket
    wsServer = ws.createServer(conn => {
        console.log("一个客户端连接了,当前连接数:", wsServer.connections.length);
        conn.on('error', err => {
            console.log("client error:", err);
        });
        conn.on('close', msg => {
            console.log("一个客户端断开了连接,当前连接数:", wsServer.connections.length);
        });
        conn.on('binary', inStream => {

            var data = Buffer.alloc(0)

            inStream.on("readable", function () {
                var newData = inStream.read()
                if (newData)
                    data = Buffer.concat([data, newData], data.length + newData.length)
            })
            inStream.on("end", function () {
                //输出一下收到的req
                var recBuf = data.slice(8, data.length);
                var req = playerProto.proto.GetPlayerRequest.decode(recBuf);
                console.log("==========>playerId:", req.playerId);


                //随便回一个response
                var player = randomPlayer();
                var resObj = playerProto.proto.GetPlayerResponse.create();
                resObj.code = 0
                resObj.info = ""
                resObj.data = {}
                resObj.data.player = player;
                resObj.data.Exist = true;
                var encode = playerProto.proto.GetPlayerResponse.encode(resObj).finish();

                //转化为自定义格式resp
                //00100100 = 36
                //seqid = 1 = [0,0,1]
                //protoid 1001 = 1111101001 = [3,233]
                var buffer = [36, 0, 0, 1, 1001 >> 8, 1001 & 0XFF, encode.length >> 8, encode.length & 0XFF]
                encode.forEach(element => {
                    buffer.push(element);
                });

                //发送
                var u8Arr = new Uint8Array(buffer);
                conn.sendBinary(u8Arr);
            })
        });

        //连接成功5s后随便发一条push吧
        setTimeout(() => {
            var player = randomPlayer();
            var pushObj = playerProto.proto.ReceivePlayerPush.create();
            pushObj.player = player
            var encode = playerProto.proto.ReceivePlayerPush.encode(pushObj).finish();

            //转化为自定义格式resp
            //00101000 = 40
            var buffer = [40, 1002 >> 8, 1002 & 0XFF, encode.length >> 8, encode.length & 0XFF]
            encode.forEach(element => {
                buffer.push(element);
            });

            //发送
            var u8Arr = new Uint8Array(buffer);
            conn.sendBinary(u8Arr);
        }, 3000)

    }).listen(port);

    wsServer.on('error', err => {
        console.log("server error: ", err);
    });
}

function randomPlayer() {
    var obj = playerProto.proto.Player.create();
    obj.name = "Name_" + Math.round(Math.random() * 1000);
    return obj;
}

main();